export default function(app) {
	app.service('authenticate', authenticate);

	function authenticate($q, $http, $stateParams, $rootScope) {
		'ngInject';

    // 登陆
    this.login = (username, password) => {
      let deferred = $q.defer();
      $http.post(`${SERVER_CONTEXT}/api/safesite/checkLogin`,{loginName: username, password: password})
        .then((resp) => {
          let data = resp.data;
          if (data.code == 'ERROR') { // 登陆失败
             deferred.reject(data);
          } else {                         // 登陆成功
            deferred.resolve(data);
            // 保存登录用户信息供登陆拦截器使用
            localStorage.setItem('userInfo',JSON.stringify(data));
            console.log(data.userId);
            $rootScope.isLogined = true;
            let from = $stateParams['from'];
            $state.go(from && from != 'login' ? from : $rootScope.defaultPage);
          }
        });
      return deferred.promise;
    }

    // 退出
    this.logout = () => {
      let deferred = $q.defer();
      $http.get(`${SERVER_CONTEXT}/api/safesite/logout`).
      then((resp) => {
        if (resp.data.code == 'OK') {
          localStorage.removeItem('userInfo');
          $rootScope.authorizationInfo = null;
          $rootScope.isLogined = false;
          deferred.resolve(resp.data);
          $state.go('login');
        } else {
          deferred.reject(resp.data);
        }
      });
      return deferred.promise;
    }
	}
}